package com.shoujifeng.snowmusic.player;

import java.io.File;
import java.io.FileInputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import android.R.integer;
import android.annotation.SuppressLint;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.animation.AnimationUtils;

import com.shoujifeng.snowmusic.entity.Mp3Info;
import com.shoujifeng.snowmusic.player.LrcProcess.LrcContent;
import com.shoujifeng.snowmusic.player.http.GlobalValue;
import com.shoujifeng.snowmusic.player.http.ServerAccess;
import com.shoujifeng.snowmusic.player.interfaces.PlayerInterface;
import com.shoujifeng.snowmusic.player.utils.LoadMask;
import com.shoujifeng.snowmusic.player.utils.MusicPlayer;

/***
 * @author 音乐播放服务
 */
@SuppressLint("NewApi")
public class PlayService extends Service implements OnBufferingUpdateListener,
		OnCompletionListener, MediaPlayer.OnPreparedListener {
	public static MediaPlayer mediaPlayer; // 媒体播放器对象
	private String path; // 音乐文件路径
	private boolean isPause; // 暂停状态
	private int current = 0; // 记录当前正在播放的音乐
	static List<Mp3Info> mp3Infos; // 存放Mp3Info对象的集合
	private int currentTime; // 当前播放进度
	private int duration; // 播放长度
	private LrcProcess mLrcProcess; // 歌词处理
	private String videoUrl; // 在线播放地址
	
	private LoadMask mLoadMask;

	private static boolean bFirst = true;
	// 初始化歌词检索值
	private int index = 0;
	// 初始化歌曲播放时间的变量
	private int CurrentTime = 0;
	// 初始化歌曲总时间的变量
	private int CountTime = 0;
	// 创建对象
	private List<LrcContent> lrcList = new ArrayList<LrcContent>(); // 存放歌词列表对象
	// 服务要发送的一些Action
	public static final String UPDATE_ACTION = "com.example.action.UPDATE_ACTION"; // 更新动作
	public static final String CTL_ACTION = "com.example.action.CTL_ACTION"; // 控制动作
	public static final String MUSIC_CURRENT = "com.example.action.MUSIC_CURRENT"; // 当前音乐播放时间更新动作
	public static final String MUSIC_DURATION = "com.example.action.MUSIC_DURATION";// 新音乐长度更新动作

	public static  PlayerInterface mInterface;
	/**
	 * handler用来接收消息，来发送广播更新播放时间
	 */
	private Handler handler = new Handler() {	
		public void handleMessage(android.os.Message msg) {
			if (msg.what == 1) {
				if (mediaPlayer != null) {
					// 获取当前音乐播放的位置
					currentTime = mediaPlayer.getCurrentPosition();
					Intent intent = new Intent();
					intent.setAction(MUSIC_CURRENT);
					intent.putExtra("currentTime", currentTime);
					// 给PlayerActivity发送广播
					sendBroadcast(intent);
					handler.sendEmptyMessageDelayed(1, 1000);
				}

			}
		};
	};

	@Override
	public void onCreate() {
		super.onCreate();
		Log.d("service", "service created");
		mediaPlayer = new MediaPlayer();
		mp3Infos = MusicPlayer.musicInfos;
		current = MusicPlayer.position;

		mLoadMask = new LoadMask(GlobalValue.mParentContext);
		/**
		 * 设置音乐播放完成时的监听器
		 */
		mediaPlayer.setOnCompletionListener(new OnCompletionListener() {

			@Override
			public void onCompletion(MediaPlayer mp) {
				SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm");
				String nowTime = sd.format(new Date());
				SharedPreferences spf = PreferenceManager
						.getDefaultSharedPreferences(PlayService.this);
				String setTime = spf.getString(ServerAccess.SET_TIME, "");
				String setStopTime = spf.getString(ServerAccess.SET_STOP_TIME,
						"");
				long nd = 1000 * 24 * 60 * 60;// 一天的毫秒数
				long nh = 1000 * 60 * 60;// 一小时的毫秒数
				long nm = 1000 * 60;// 一分钟的毫秒数
				long ns = 1000;// 一秒钟的毫秒数
				long diff;
				long min = 0;
				try {
					diff = sd.parse(nowTime).getTime()
							- sd.parse(setTime).getTime();
					min = diff % nd % nh / nm;// 计算差多少分钟

				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				if (setTime.equals("") || Long.parseLong(setStopTime) - min > 0) {
					// 单曲循环
					if (MusicPlayer.PLAY_ORDER == 3) {
						mediaPlayer.start();
					}
					// 全部循环
					else if (MusicPlayer.PLAY_ORDER == 4) {

						if (MusicPlayerActivity.isOnline == true) {
							MusicPlayer.position++;
							if (MusicPlayer.position == MusicPlayerActivity.mOlineMusicList
									.size()) {
								MusicPlayer.position = 0;
							}
							playNet(MusicPlayer.position);
						} else {
							current++;
							MusicPlayer.position = current;
							if (current > mp3Infos.size() - 1) { // 变为第一首的位置继续播放
								current = 0;
							}
							path = mp3Infos.get(current).getUrl();
							play(0);
						}
					}
					// 顺序播放
					else if (MusicPlayer.PLAY_ORDER == 0) {
						if (MusicPlayerActivity.isOnline == true) {
							MusicPlayer.position++;
							if (MusicPlayer.position < MusicPlayerActivity.mOlineMusicList
									.size()) {
								playNet(MusicPlayer.position);
							}

						} else {
							current++;
							MusicPlayer.position = current;
							if (current <= mp3Infos.size() - 1) {
								path = mp3Infos.get(current).getUrl();
								play(0);
							}

						}

					}
					// 随机播放
					else if (MusicPlayer.PLAY_ORDER == 1) {
						if (MusicPlayerActivity.isOnline == true) {
							MusicPlayer.position = getRandomIndex(MusicPlayerActivity.mOlineMusicList
									.size() - 1);
							playNet(MusicPlayer.position);
						} else {
							current = getRandomIndex(MusicPlayer.musicInfos
									.size() - 1);
							MusicPlayer.position = current;
							path = mp3Infos.get(current).getUrl();
							play(0);
						}
					}
				}

			}
		});

	}

	/**
	 * 获取随机位置
	 * 
	 * @param end
	 * @return
	 */
	protected int getRandomIndex(int end) {
		int index = (int) (Math.random() * end);
		return index;
	}

	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}

	@Override
	public void onStart(Intent intent, int startId) {
		// 在线播放
		if (MusicPlayerActivity.isOnline == true && MusicPlayer.MUSCI_MSG == 1) {
			playNet(0);
		} else {
			// 播放本地的
			if (MusicPlayerActivity.isOnline == false) {
				// 歌曲路径
				path = MusicPlayer.musicInfos.get(MusicPlayer.position)
						.getUrl();
				// 当前播放歌曲的在mp3Infos的位置
				current = MusicPlayer.position;
			}
			// 直接播放音乐
			if (MusicPlayer.MUSCI_MSG == 1
					&& MusicPlayerActivity.isOnline == false) {

				play(0);
			}
			// 暂停
			else if (MusicPlayer.MUSCI_MSG == 2) {
				pause();
			}
			// 停止
			else if (MusicPlayer.MUSCI_MSG == 3) {
				stop();
			}
			// 继续播放
			else if (MusicPlayer.MUSCI_MSG == 4) {
				resume();
			}
			// 上一首
			else if (MusicPlayer.MUSCI_MSG == 5) {
				previous();
			}
			// 下一首
			else if (MusicPlayer.MUSCI_MSG == 6) {
				next();
			}
		}
		super.onStart(intent, startId);

	}

	/**
	 * 播放音乐
	 * 
	 * @param position
	 */
	private void play(int currentTime) {
		try {

			// 把各项参数恢复到初始状态
			mediaPlayer.reset();

			mediaPlayer.setDataSource(path);
			// 进行缓冲
			mediaPlayer.prepare();
	//		 注册一个监听器
			mediaPlayer
					.setOnPreparedListener(new PreparedListener(currentTime));
			handler.sendEmptyMessage(1);

			getLrcUrl((int)MusicPlayer.musicInfos.get(current).getId());


			MusicPlayerActivity.lay3_musicName.setText(mp3Infos.get(current)
					.getTitle());
			MusicPlayerActivity.lay3_playerName.setText(mp3Infos.get(current)
					.getArtist());
			
			//触发回调
			if(mInterface != null)
				mInterface.playNext(MusicPlayer.position);
			
			// 启动线程
			mHandler.post(mRunnable);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 暂停音乐
	 */
	private void pause() {
		if (mediaPlayer != null && mediaPlayer.isPlaying()) {
			mediaPlayer.pause();
			isPause = true;
		}
	}

	private void resume() {
		if (isPause) {
			mediaPlayer.start();
			
			isPause = false;
		}
	}

	/**
	 * 上一首
	 */
	private void previous() {
		if(MusicPlayerActivity.isOnline==true){
			playNet(0);
		}
		else{
			Intent sendIntent = new Intent(UPDATE_ACTION);
			sendIntent.putExtra("current", current);
			// 发送广播，将被Activity组件中的BroadcastReceiver接收到
			sendBroadcast(sendIntent);
			play(0);
		}
	}

	/**
	 * 下一首
	 */
	private void next() {
		if(MusicPlayerActivity.isOnline==true){
			playNet(0);
		}
		else{
			Intent sendIntent = new Intent(UPDATE_ACTION);
			sendIntent.putExtra("current", current);
			// 发送广播，将被Activity组件中的BroadcastReceiver接收到
			sendBroadcast(sendIntent);
			play(0);
		}
	}

	/**
	 * 停止音乐
	 */
	private void stop() {
		if (mediaPlayer != null) {
			mediaPlayer.stop();
			try {
				// 在调用stop后如果需要再次通过start进行播放,需要之前调用prepare函数
				mediaPlayer.prepare();

			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public void onDestroy() {

		if (mediaPlayer != null) {
			mediaPlayer.stop();
			mediaPlayer.release();
			mediaPlayer = null;
		}

	}

	/**
	 * 
	 * 实现一个OnPrepareLister接口,当音乐准备好的时候开始播放
	 * 
	 */
	private final class PreparedListener implements OnPreparedListener {
		private int currentTime;

		public PreparedListener(int currentTime) {
			this.currentTime = currentTime;
		}

		@Override
		public void onPrepared(MediaPlayer mp) {
			// 开始播放
			mediaPlayer.start();
			// 如果音乐不是从头播放
			if (currentTime > 0) {
				mediaPlayer.seekTo(currentTime);
			}
			Intent intent = new Intent();
			intent.setAction(MUSIC_DURATION);
			duration = mediaPlayer.getDuration();
			// 通过Intent来传递歌曲的总长度
			intent.putExtra("duration", duration);
			sendBroadcast(intent);
		}
	}

	Handler mHandler = new Handler();
	// 歌词滚动线程
	Runnable mRunnable = new Runnable() {

		@Override
		public void run() {
			// TODO Auto-generated method stub
			try {
				int lrcIndex = LrcIndex();
				if(lrcIndex > 0) {
					MusicPlayerActivity.lrc_view.SetIndex(lrcIndex);
					MusicPlayerActivity.lrc_view.invalidate();
				}
				
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			mHandler.postDelayed(mRunnable, 1000);
		}
	};
	
	

	/**
	 * 歌词同步处理类
	 * 
	 * @throws ParseException
	 */
	public int LrcIndex() throws ParseException {
		if (mediaPlayer.isPlaying()) {
			// 获得歌曲播放在哪的时间
			CurrentTime = mediaPlayer.getCurrentPosition();
			// 获得歌曲总时间长度
			CountTime = mediaPlayer.getDuration();
			MusicPlayerActivity.progressBar.setProgress(CurrentTime);
			MusicPlayerActivity.progressBar.setMax(CountTime);
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat("mm:ss");

			MusicPlayerActivity.whenTxt.setText(simpleDateFormat.format(
					CurrentTime).toString());

			MusicPlayerActivity.countTimeTxt.setText(simpleDateFormat.format(
					CountTime).toString());
			
			

		}
		if (CurrentTime < CountTime) {

			for (int i = 0; i < lrcList.size(); i++) {
				if (i < lrcList.size() - 1) {
					if (CurrentTime < lrcList.get(i).getLrc_time() && i == 0) {
						index = i;
					}
					if (CurrentTime > lrcList.get(i).getLrc_time()
							&& CurrentTime < lrcList.get(i + 1).getLrc_time()) {
						index = i;
					}
				}
				if (i == lrcList.size() - 1
						&& CurrentTime > lrcList.get(i).getLrc_time()) {
					index = i;
				}
			}
		}
		return index;
	}

	/**
	 * 播放在线音乐
	 * 
	 * @param playPosition
	 */
	private void playNet(int playPosition) {
		musicPrepare(playPosition);
		/*
		try {
			mediaPlayer.reset();// 把各项参数恢复到初始状态

			mediaPlayer.setDataSource(MusicPlayerActivity.mOlineMusicList
					.get(MusicPlayer.position).get(ServerAccess.MUSIC_FILE)
					.toString());
			mediaPlayer.prepare();// 进行缓冲
			
			mediaPlayer.setOnPreparedListener(new MyPreparedListener(
					playPosition));
			mHandler.post(mRunnable);
			MusicPlayerActivity.lay3_musicName.setText(MusicPlayerActivity.mOlineMusicList
					.get(MusicPlayer.position).get(ServerAccess.MUSIC_NAME)
					.toString());
			MusicPlayerActivity.lay3_playerName.setText(MusicPlayerActivity.mOlineMusicList
					.get(MusicPlayer.position).get(ServerAccess.SINGER)
					.toString());
			MusicPlayerActivity.setMusicImg();
			
			HashMap<String, Object> map = MusicPlayerActivity.mOlineMusicList
					.get(MusicPlayer.position);
			
			getLrcUrl(Integer.parseInt(map.get("index").toString()));
			
			
			//触发回调
			if(mInterface != null)
				mInterface.playNext(MusicPlayer.position);
		} catch (Exception e) {
			// TODO: handle exception
		}
		*/
	}
	
	private void musicPrepare(final int position) {
		
		if(MusicPlayerActivity.LOADMASK != null)
			MusicPlayerActivity.LOADMASK.startLoad("在线歌曲缓冲中...");
		new AsyncTask<Integer, Integer, Integer>() {
 
			@Override
			protected Integer doInBackground(Integer... params) {
				try {
					mediaPlayer.reset();// 把各项参数恢复到初始状态
					/**
					 * 通过MediaPlayer.setDataSource()
					 * 的方法,将URL或文件路径以字符串的方式传入.使用setDataSource ()方法时,要注意以下三点:
					 * 1.构建完成的MediaPlayer 必须实现Null 对像的检查.
					 * 2.必须实现接收IllegalArgumentException 与IOException
					 * 等异常,在很多情况下,你所用的文件当下并不存在. 3.若使用URL 来播放在线媒体文件,该文件应该要能支持pragressive
					 * 下载.
					 */
					mediaPlayer.setDataSource(MusicPlayerActivity.mOlineMusicList
							.get(MusicPlayer.position).get(ServerAccess.MUSIC_FILE)
							.toString());
					mediaPlayer.prepare();// 进行缓冲
					
					publishProgress(0);
				} catch (Exception e) {
					// TODO: handle exception
				}
				return null;
			}

			@Override
			protected void onProgressUpdate(Integer... values) {

				mediaPlayer.setOnPreparedListener(new MyPreparedListener(
						position));
				mHandler.post(mRunnable);
				MusicPlayerActivity.lay3_musicName.setText(MusicPlayerActivity.mOlineMusicList
						.get(MusicPlayer.position).get(ServerAccess.MUSIC_NAME)
						.toString());
				MusicPlayerActivity.lay3_playerName.setText(MusicPlayerActivity.mOlineMusicList
						.get(MusicPlayer.position).get(ServerAccess.SINGER)
						.toString());
				MusicPlayerActivity.setMusicImg();
				
				HashMap<String, Object> map = MusicPlayerActivity.mOlineMusicList
						.get(MusicPlayer.position);
				
				getLrcUrl(Integer.parseInt(map.get("index").toString()));
				
				if(MusicPlayerActivity.LOADMASK != null)
					MusicPlayerActivity.LOADMASK.stopLoad();
				//触发回调
				if(mInterface != null)
					mInterface.playNext(MusicPlayer.position);
					
				if(bFirst) {
					musicPrepare(position);
					bFirst = false;
				}
				
				super.onProgressUpdate(values);
			}
			
			
		}.execute(0);
	}
	
private void getLrcUrl(final int index) {
		
		new AsyncTask<Integer, String, Integer>() {

			@Override
			protected Integer doInBackground(Integer... params) {

				try {
					ServerAccess serverAccess = new ServerAccess(null);
					String lrc = serverAccess.getLrcUrl(index);
					
					if(!lrc.equals("")) {
						lrc = serverAccess.getLrc(lrc);
					}
					
					publishProgress(lrc);
				} catch (Exception e) {
					// TODO: handle exception
				}
				return null;
			}

			@Override
			protected void onProgressUpdate(String... values) {
				
				//这里去获取网络LRC
				//values[0]  是歌词
				if(!values[0].equals("")) {
					// 初始化歌词配置
					mLrcProcess = new LrcProcess();
					// 读取歌词文件
					mLrcProcess.readLRC(values[0]);
					// 传回处理后的歌词文件
					lrcList = mLrcProcess.getLrcContent();
					MusicPlayerActivity.lrc_view.setmLrcList(lrcList);
					// 切换带动画显示歌词
					MusicPlayerActivity.lrc_view.setAnimation(AnimationUtils
							.loadAnimation(PlayService.this, R.anim.alpha_z));
				}
				else {
					//没歌词
				}
				super.onProgressUpdate(values);
			}
			
			
		}.execute(0);
	}


	private final class MyPreparedListener implements
			android.media.MediaPlayer.OnPreparedListener {
		private int playPosition;

		public MyPreparedListener(int playPosition) {
			this.playPosition = playPosition;
		}

		@Override
		public void onPrepared(MediaPlayer mp) {
			mediaPlayer.start();// 开始播放
			if (playPosition > 0) {
				mediaPlayer.seekTo(playPosition);
			}
		}
	}

	@Override
	public void onPrepared(MediaPlayer arg0) {
		// TODO Auto-generated method stub
		arg0.start();
		Log.e("mediaPlayer", "onPrepared");
	}

	@Override
	public void onCompletion(MediaPlayer arg0) {
		// TODO Auto-generated method stub
		Log.e("mediaPlayer", "onCompletion");
	}

	@Override
	public void onBufferingUpdate(MediaPlayer arg0, int arg1) {
		// TODO Auto-generated method stub

	}

}